package com.fenqing.leetcode.code.t0_200.t0_100;

import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;

import java.util.Arrays;

/**
 * @author fenqing
 */
public class Topic034 extends Topic {
    /**
     * 构造器
     *
     * @param input1 输入
     * @param input2 输入
     */
    public Topic034(String input1, String input2) {
        super(input1, input2);
    }

    @Execute
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0) {
            return new int[]{-1, -1};
        }
        if (nums.length == 1 && nums[0] == target) {
            return new int[]{0, 0};
        }
        int index = binarySearch(nums, target, 0, nums.length - 1, 1);
        if (index == -1) {
            return new int[] {-1, -1};
        }
        int index2 = binarySearch(nums, target, index, nums.length - 1, 2);
        return new int[]{index, index2 - 1};
    }

    public int binarySearch(int[] nums, int target, int left, int right, int type) {
        while (left < right) {
            int mid = (left + right) / 2;
            int midValPrev = mid - 1 < 0 ? Integer.MIN_VALUE : nums[mid - 1];
            int midVal = nums[mid];
            if (type == 1) {
                if (midValPrev < target && midVal == target) {
                    return mid;
                } else if (midVal < target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
            if (type == 2) {
                if (midValPrev == target && midVal > target) {
                    return mid;
                } else if (midVal <= target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }

        }
        if (type == 1 && nums[left] == target && (left - 1 < 0 || nums[left - 1] < target)) {
            return left;
        } else if (type == 2) {
            if (nums[left - 1] == target && nums[left] > target) {
                return left;
            } else if (left + 1 == nums.length && nums[left] == target) {
                return left + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Topic034 topic034 = new Topic034(
                """
                        [1,2,3]
                        """,
                "1"
        );
        int[] run = topic034.run();
        System.out.println(Arrays.toString(run));
    }

}
